package com.phpxiu.app.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.phpxiu.app.adapter.LanguageListAdapter;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.list.Language;
import com.phpxiu.app.view.UserSetting;

/**
 * Created by 吴金洲 on 2016/8/8
 */
public class LanguageOptionsWin extends Dialog implements View.OnClickListener,AdapterView.OnItemClickListener {
    private ListView mListView;
    private int mCurrentLanguage;
    private UserSetting userSetting;
    private int selected=-1;
    private LanguageListAdapter mAdapter;

    public LanguageOptionsWin(UserSetting context, int currentLanguage) {
        super(context, R.style.dialog);
        mCurrentLanguage=currentLanguage;
        userSetting=context;
        init(context);
    }

    private void init(Context context){
        setContentView(R.layout.user_setting_language_win);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        mListView=(ListView)findViewById(R.id.language_options_list_view);
        mListView.setDivider(null);
        mListView.setOnItemClickListener(this);
        mAdapter=new LanguageListAdapter(context,userSetting.LANGUAGES);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof Language){
            selected=((Language)view.getTag()).getCode();
            for (Language l:userSetting.LANGUAGES){
                l.setSelected(false);
            }
            userSetting.LANGUAGES.get(position).setSelected(true);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                save();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //返回键盘事件
        if(keyCode==KeyEvent.KEYCODE_BACK){
            save();
            return false;
        }else{
            return super.onKeyDown(keyCode,event);
        }
    }

    public void save(){
        if(selected==-1||selected==mCurrentLanguage){
            dismiss();
            return;
        }
        if(userSetting!=null){
            userSetting.switchLanguage(selected);
        }
        dismiss();
    }
}
